package com.atguigu.guli.service.ucenter.controller.api;

import com.atguigu.guli.common.util.HttpClientUtils;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.helper.JwtHelper;
import com.atguigu.guli.service.base.helper.JwtInfo;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.ucenter.entity.Member;
import com.atguigu.guli.service.ucenter.entity.UcenterProperties;
import com.atguigu.guli.service.ucenter.service.MemberService;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author Miluo
 * @description 微信登陆应用层
 **/
@Controller

@Api(tags = "微信登陆")
@RequestMapping("/api/ucenter/wx")
@Slf4j
public class ApiWxController {
    @Autowired
    private UcenterProperties ucenterProperties;

    @Autowired
    private MemberService memberService;



    @GetMapping("/callback")
    public String getCode2(String code,String state,HttpSession session){
        log.info("callback被调用");
        log.info("code = " + code);
        log.info("state = " + state);

        if (StringUtils.isEmpty(code)){
            log.error("非法回调请求");
            throw new GuliException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }

        String wx_open_state = (String) session.getAttribute("wx_open_state");
        if (!state.equals(wx_open_state)){
            log.error("非法回调请求");
            throw new GuliException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        url = String.format(url,ucenterProperties.getAppId(),ucenterProperties.getAppSecret(),code);

        HttpClientUtils httpClientUtils = new HttpClientUtils(url);

        String result = "";

        try {
            httpClientUtils.get();
            result = httpClientUtils.getContent();
            System.out.println(result);
        } catch (Exception e) {
            log.error("获取token失败");
            throw new GuliException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }

        Gson gson = new Gson();
        HashMap hashMap = gson.fromJson(result, HashMap.class);
        String accessToken = (String) hashMap.get("access_token");
        String openid = (String) hashMap.get("openid");

        log.info("accessToken = " + accessToken);
        log.info("openid = " + openid);

        Member member =  memberService.selectByOpenid(openid);

        if (member == null){


            url = "https://api.weixin.qq.com/sns/userinfo?" +
                    "access_token=%s" +
                    "&openid=%s";

            url = String.format(url,accessToken,openid);

            httpClientUtils = new HttpClientUtils(url);

            String info = null;
            try {
                httpClientUtils.get();
                info = httpClientUtils.getContent();
            } catch (Exception e) {
                log.error("获取信息失败");
                throw new GuliException(ResultCodeEnum.FETCH_USERINFO_ERROR);
            }

            HashMap userInfo = gson.fromJson(info, HashMap.class);
            String nickname = (String) userInfo.get("nickname");
            String headimgurl = (String) userInfo.get("headimgurl");
            Double sex = (Double) userInfo.get("sex");

            member = new Member();
            member.setNickname(nickname);
            member.setSex(sex.intValue());
            member.setAvatar(headimgurl);
            member.setOpenid(openid);
            memberService.save(member);

        }

        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setId(member.getId());
        jwtInfo.setNickname(member.getNickname());
        jwtInfo.setAvatar(member.getAvatar());

        String token = JwtHelper.createToken(jwtInfo);

        return "redirect:http://localhost:3333?token=" + token;


    }

    @GetMapping("/login")
    public String getCode(HttpSession session){

        String url = "https://open.weixin.qq.com/connect/qrconnect?" +
                "appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code&" +
                "scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String appId = ucenterProperties.getAppId();
        String appSecret = ucenterProperties.getAppSecret();
        String redirectUri = ucenterProperties.getRedirectUri();

        try {
            redirectUri = URLEncoder.encode(redirectUri,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new GuliException(ResultCodeEnum.URL_ENCODE_ERROR);
        }
        String state = UUID.randomUUID().toString();
        log.info("1生成 state = " + state);
        session.setAttribute("wx_open_state",state);
        url = String.format(url,appId,redirectUri,state);


        return "redirect:" + url;
    }
}
//http://guli.shop/api/ucenter/wx/callback8160response_type=code?code=091jun000cTqAK1lbt000B6t5o3jun0b&state=7ce81702-3b16-4189-8fae-25be45e0b615